package com.example.libraryapp.adapter.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 伍凯铭
 * @since 2020/4/16
 */
public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {

    protected List<T> mDatas;

    protected Context mContext;

    private OnItemClickListener mOnItemClickListener = null;

    public BaseAdapter(Context context) {
        this.mDatas = new ArrayList<>();
        this.mContext = context;
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(getLayoutId(viewType), parent,false);
        return new BaseViewHolder(view,mOnItemClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        T t = getItem(position);
        bindData(holder,t);
    }

    @Override
    public int getItemCount() {
        return mDatas != null ? mDatas.size() : 0;
    }

    public T getItem(int position) {
        if (position >= mDatas.size()) {
            return null;
        }
        return mDatas.get(position);
    }

    public List<T> getDatas(){
        return mDatas;
    }

    public void refreshData(List<T> list) {
        mDatas.clear();
        if(list != null) {
            mDatas.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void clearData() {
        mDatas.clear();
        notifyDataSetChanged();
    }

    public void addData(List<T> list) {
        if(list != null) {
            mDatas.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public abstract void bindData(BaseViewHolder holder, T data);

    public abstract int getLayoutId(int viewType);

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }
}
